<template>
    <div class="tableList">
        <el-table :data="tableData" border style="width: 100%;" @sort-change="handleSortChange"
            :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
            :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" v-loading="loading"
            element-loading-text="加载中" element-loading-background="rgba(250, 250, 250, 0.5)" :row-key="getRowKeys"
            element-loading-spinner="el-icon-loading" @selection-change="handleSelectionChange" @cell-click='cellClick'
            :cell-class-name="({row, column}) => {if(column.label == '工单编号'){return 'workordercode'}}" 
            ref="tabList" :key="toUpdateTableKey">
            <el-table-column type="selection" width="55" :reserve-selection='true'>
            </el-table-column>
            <el-table-column v-for="(item,index) in tableGroup" :key="item.label" :label="item.name"
                :sortable="item.sortable" :min-width="item.width" :show-overflow-tooltip="item.label != 'list'"
                :fixed="index === 0 || index == 1"
                >
                <template slot-scope="scope">
                    <code v-if="item.label == 'state'">
                        <span class="circle" :style="{background:state[scope.row[item.label]].c}"></span>
                        {{state[scope.row[item.label]].n}}
                    </code>

                    <code v-else-if="item.label == 'code'">
                        <span class="urgent iconfont icon-0-42" v-if="scope.row.isUrgent == 1"></span>
                        <div class="status" @click="watch(scope.row)">
                            <span :title="scope.row[item.label]"
                                :style="{color:computedColor(scope.row),width:(scope.row.isDelay == 1 ? '78' : '100')  + '%'}"
                                >{{scope.row[item.label]}}</span>
                            <span v-if="scope.row.isDelay == 1">延期</span>
                        </div>
                    </code>

                    <code v-else-if="item.label == 'relatedSalesInfoVo'">
                        <div class="status">
                            <span style="width:100%;color:#409EFF">{{computedInfoVo(scope.row[item.label])}}</span>
                        </div>
                    </code>

                    <code class="progress" v-else-if="item.label == 'list'">
                        <div class="item_progress" v-for="(k,ind) in scope.row[item.label]" :key="ind">
                            <div class="progress_circle" @click="skip(scope.row.code,k.processCode)">
                                <el-tooltip placement="bottom">
                                    <div slot="content">已报工良品数：{{k.goodProductNumber}}；工序计划数：{{k.planedNumber}}</div>
                                    <el-progress type="circle" :percentage="k.rate || 0" :status="customStatus(k.rate)"
                                        :stroke-width="8">
                                    </el-progress>
                                </el-tooltip>
                                <div class="line" v-if="ind != scope.row[item.label].length - 1"
                                    :class="customClass(scope.row.state,k.rate)"></div>
                            </div>
                            <span :title="k.processName">{{k.processName}}</span>
                        </div>
                    </code>

                    <code v-else>
                        <code v-if='customImgSet(item.label, scope.row)'>
                            <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                <img :src="$global.uploadUrl + k.url" alt=""
                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i" class="customImg"
                                    @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'>
                            </p>
                            <p v-else>
                                <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url" alt=""
                                    class="customImg"
                                    @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                <span class='customImgMoreBox'>
                                    <div class='customImgMore'
                                        @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                        <el-popover placement="top" max-width="400" trigger="hover">
                                            <div class='customImgMore' slot="reference">
                                                +{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                            <img :src="$global.uploadUrl + k.url" alt=""
                                                v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                style="margin-right:10px" width='60px' height='60px'
                                                @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))">
                                        </el-popover>
                                    </div>
                                    <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url" alt=""
                                        class="customImg">
                                </span>
                            </p>
                        </code>
                        <code v-else>
                            <code v-if="customSelectSet(item.label, scope.row)">
                                <span v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                    :style="customSelectStyle(item.label, scope.row, k)" class="customSelect">
                                    {{ k }}
                                </span>
                            </code>
                            <code v-else>
                                {{scope.row[item.label]}}
                            </code>
                        </code>
                    </code>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
                <template slot-scope="scope">
                    <div class="btnCell">
                        <el-button type="text" size="small" @click="watch(scope.row)" v-hasPermis="'button.edit'">查看
                        </el-button>
                        <el-dropdown trigger="click" size="small">
                            <el-button type="text" size="small">操作</el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item class="dropdowncode"
                                    @click.native="btnSet('s',{id:scope.row.id,state:scope.row.state})"
                                    :disabled="isDisabled('s',scope.row.state)">
                                    <el-button type="text" size="mini" icon="el-icon-video-play"
                                        v-hasPermis="'button.start'" :disabled="isDisabled('s',scope.row.state)">开始
                                    </el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class="dropdowncode"
                                    @click.native="btnSet('r',{id:scope.row.id,state:scope.row.state})"
                                    :disabled="isDisabled('r',scope.row.state)">
                                    <el-button type="text" size="mini" icon="el-icon-back" v-hasPermis="'button.recall'"
                                        :disabled="isDisabled('r',scope.row.state)">撤回</el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class="dropdowncode"
                                    @click.native="btnSet('e',{id:scope.row.id,state:scope.row.state})"
                                    :disabled="isDisabled('e',scope.row.state)">
                                    <el-button type="text" size="mini" icon="el-icon-switch-button"
                                        v-hasPermis="'button.end'" :disabled="isDisabled('e',scope.row.state)">结束
                                    </el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class="dropdowncode" @click.native="cancel('c',{id:scope.row.id,state:scope.row.state})"
                                    :disabled="isDisabled('c',scope.row.state)">
                                    <el-button type="text" size="mini" icon="el-icon-circle-close"
                                        v-hasPermis="'button.cancel'" :disabled="isDisabled('c',scope.row.state)">取消
                                    </el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class="dropdowncode" @click.native="print(scope.row.id)">
                                    <el-button type="text" size="mini" icon="el-icon-printer"
                                        v-hasPermis="'button.print'">打印</el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class="dropdowncode"
                                    @click.native="copy(scope.row.id,scope.row.code,scope.row.relatedSalesInfoVo)">
                                    <el-button type="text" size="mini" icon="el-icon-copy-document"
                                        v-hasPermis="'button.copy'">复制
                                    </el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class="dropdowncode" @click.native="delWorkOrder(scope.row.id)">
                                    <el-button type="text" size="mini" icon="el-icon-delete"
                                        v-hasPermis="'button.delete'">删除</el-button>
                                </el-dropdown-item>
                                <el-dropdown-item class='dropdowncode content__1s_xr' @click.native="getUrgent({
                                        value:scope.row.isUrgent ? 0 : 1,
                                        ids: scope.row.id
                                    })">
                                    <el-button type="text" size="mini">
                                        {{!scope.row.isUrgent ? '加急' : '取消加急'}}
                                    </el-button>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </template>
            </el-table-column>
            <div slot="empty">
                <el-empty :image-size="100"></el-empty>
            </div>
        </el-table>
        <el-pagination v-if="tableData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :page-sizes="[10,20,50,100]" :page-size="searchForm.limit" layout="total,prev, pager, next,sizes"
            :total="total" background :current-page="currentPage">
        </el-pagination>
        <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
            <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial'
                @change='handleCarousel' ref='carousel'>
                <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                    <img :src="item.url" alt="" class='carouselImg'>
                </el-carousel-item>
            </el-carousel>
            <div class='imgDownLoad' @click='imgDownLoad'>
                <span class='el-icon-download'></span>
                下载
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        workOrderList,
        workOrderDel,
        workOrderHandle,
        wosHandle,
        urgent
    } from '@/api/produceController'
    import {
        exportTable
    } from "@/mixin"
    export default {
        data() {
            return {
                tableData: [],
                toUpdateTableKey:false,
                loading: false,
                multipleSelection: [],
                total: 0,
                currentPage: 0,
                state: {
                    0: {
                        n: '未开始',
                        c: 'rgb(255,153,0)'
                    },
                    1: {
                        n: '执行中',
                        c: 'rgb(2, 185, 128)'
                    },
                    2: {
                        n: '已结束',
                        c: 'rgb(24, 145, 255)'
                    },
                    3: {
                        n: '已取消',
                        c: 'rgb(255, 59, 48)'
                    }
                },
                customImgData: {
                    visible: false,
                    list: [],
                    title: '',
                    initial: 0,
                    num: 0
                }
            }
        },
        props: {
            tableGroup: {
                type: Array,
                default: () => []
            },
            searchForm: {
                type: Object,
                default: () => ({})
            }
        },
        mixins: [exportTable],
        computed: {
            computedInfoVo() {
                return info => {
                    if (info) {
                        return info.salesCode + ' ' + '(' + '共' + info.detailNum + '单' + ')'
                    } else {
                        return '-'
                    }
                }
            },
            computedColor() {
                return row => {
                    return this.state[row.state].c
                }
            },
            isDisabled() {
                return (way, state) => {
                    let relState = null
                    switch (way) {
                        case 's':
                            relState = state == 1 || state == 2 || state == 3
                            break;
                        case 'r':
                            relState = state == 0 || state == 3
                            break;
                        case 'c':
                            relState = state == 3
                            break;
                        case 'e':
                            relState = state == 2 || state == 3
                            break;
                    }
                    return relState
                }
            }
        },
        methods: {
            customClass(state, rate) {
                if (state == 0) {
                    return 'no_start'
                } else if (rate == 100) {
                    return 're_c'
                } else if (rate >= 0 && rate < 100) {
                    return 'no_c'
                }
            },
            customStatus(rate) {
                if (rate == 100) return 'success'
            },
            //工单列表
            getWorkOrderList:async function (data){                
                this.loading = true
                const res = await workOrderList(data)
                if (res.code == 200) {
                    this.tableData = res.data.data.records
                    this.total = res.data.data.total
                    this.tableData.map((item, i) => {
                        item.index = (res.data.data.current - 1) * 10 + (i + 1)
                        if (item.customFieldVos != null) {
                            item.customFieldVos.map(k => {
                                item[k.customFieldId] = k.value
                            })
                        }
                    })
                }
                //当前页大于第一页时 点击筛选方案回到第一页且选中第一页
                this.currentPage = this.searchForm.page
                this.$emit('getTotal', res.data.data.total)
                this.$emit('getSecondGroupInfo',{
                    key:res.data.secondGroupColumnName,
                    typeCountData:res.data.typeCountData
                })
                this.loading = false
            },
            skip(code, processCode) {
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path: '/productionManagement/jobBooking',
                    query: {
                        code,
                        processCode
                    }
                })
            },
            getRowKeys(row) {
                return row.id
            },
            //工单操作
            getWorkOrderHandle: async function (data, tit) {
                const res = await workOrderHandle(data, tit)
                if (res.code == 200) {
                    this.getWorkOrderList(this.searchForm)
                    this.utils.showMsg(`${tit}成功`, 'success')
                }
            },
            //工单删除
            getWorkOrderDel(data) {
                workOrderDel(data).then(res => {
                    if (res.code == 200) {
                        let toggleIndex = this.multipleSelection.findIndex(i => i.id == data.id)
                        toggleIndex != -1 && this.multipleSelection.splice(toggleIndex, 1)
                        if (!this.multipleSelection.length) this.$refs.tabList.clearSelection()
                        this.getWorkOrderList(this.searchForm)
                        this.utils.showMsg('删除成功', 'success')
                    }
                })
            },
            //打印
            print(id) {
                this.$emit('getPrint', id)
            },
            handleSortChange({
                order,
                prop
            }) {},
            //批量操作
            getWosHandle(data) {
                wosHandle(data).then(res => {
                    if (res.code == 200) {
                        this.getWorkOrderList(this.searchForm)
                        this.$refs.tabList.clearSelection()
                        this.utils.showMsg(
                            `开始共操作${res.data.total}条，成功${res.data.successNum}条，失败${res.data.failNum}条`,
                            'success')
                    }
                })
            },
            //加急操作
            getUrgent(data) {
                urgent(data).then(res => {
                    if (res.code == 200) {
                        this.getWorkOrderList(this.searchForm)
                        this.$refs.tabList.clearSelection()
                        this.utils.showMsg(res.data, 'success')
                    }
                })
            },
            handleSelectionChange(selection) {
                this.multipleSelection = selection
                let ids = ''
                ids = selection.map(i => i.id).toString()
                this.$emit('getCheckedId', ids)
            },
            //删除 
            confirmDel(id) {
                this.getWorkOrderDel({
                    id
                })
                let totalPage = Math.ceil((this.total - 1) / this.searchForm.limit)
                let currentPage = this.searchForm.page > totalPage ? totalPage : this.searchForm.page
                this.searchForm.page = currentPage < 1 ? 1 : currentPage
            },
            //开始--取消--撤回--结束
            btnSet(o, scope) {
                let {
                    id,
                    state
                } = scope
                const enumState = {
                    s: {
                        tit: '开始',
                        targetState: {
                            0: 1
                        }
                    },
                    r: {
                        tit: '撤回',
                        targetState: {
                            1: 0,
                            2: 1
                        }
                    },
                    e: {
                        tit: '结束',
                        targetState: {
                            0: 2,
                            1: 2
                        }
                    },
                    c: {
                        tit: '取消',
                        targetState: {
                            0: 3,
                            1: 3,
                            2: 3
                        }
                    }
                }
                this.getWorkOrderHandle({
                    id,
                    state: enumState[o].targetState[state]
                }, enumState[o].tit)
            },
            //取消
            cancel(o, scope) {
                this.$confirm('工单取消将无法恢复，是否继续', '确定取消工单', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    customClass: 'messagebox',
                    type: 'warning'
                }).then(() => {
                    this.btnSet(o, scope)
                }).catch(() => {})
            },
            //删除
            delWorkOrder(id) {
                this.$confirm('删除后，将同时删除关联的工单、任务和报工，且不可恢复。', '确定删除工单', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    customClass: 'messagebox',
                    confirmButtonClass: 'dangerBtn',
                    type: 'warning'
                }).then(() => {
                    this.confirmDel(id)
                }).catch(() => {})
            },
            //复制
            copy(id, code, relatedSalesInfoVo) {
                let query = {
                    id,
                    code,
                    salesId: relatedSalesInfoVo != null ? relatedSalesInfoVo.salesId : '',
                    salesCode: relatedSalesInfoVo != null ? relatedSalesInfoVo.salesCode : ''
                }
                Object.keys(query).forEach(key => {
                    if (query[key] == '') delete query[key]
                })
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path: '/productionManagement/copy',
                    query
                })
            },
            //查看
            watch(row) {
                let query = {}
                if (row.relatedSalesInfoVo != null) {
                    query = {
                        id: row.id,
                        code: row.code,
                        state: row.state,
                        salesId: row.relatedSalesInfoVo.salesId,
                        salesCode: row.relatedSalesInfoVo.salesCode
                    }
                } else {
                    query = {
                        id: row.id,
                        code: row.code,
                        state: row.state
                    }
                }
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path: '/productionManagement/edit',
                    query
                })
            },
            //跳转至销售订单
            cellClick(row, column) {
                if (column.label == '关联单据' && row.relatedSalesInfoVo != null) {
                    this.$store.commit('setPage', this.searchForm.page);
                    this.$store.commit('setRouter', this.$route.path);
                    this.$router.push({
                        path: '/productionManagement/salesOrder/edit',
                        query: {
                            id: row.relatedSalesInfoVo.salesId
                        }
                    })
                }
            },
            // 自定义字段 复选框/单选框 列
            customSelectSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if ((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess
                                    .fieldType == 'selectChecked') && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            customSelectList(t, d) {
                if (d[t] == '' || d[t] == '[]') {
                    return []
                } else {
                    let data = []
                    try {
                        data = JSON.parse(d[t])
                    } catch {
                        data = d[t].split(',')
                        data[0] == '' ? data = [] : ''
                    }
                    data === Number(data) ? data = [data] : ''
                    return data
                }
            },
            customSelectStyle(t, d, v) {
                let style = {}
                if (d.customFieldVos != null) {
                    let obj = d.customFieldVos.find(res => {
                        return res.customFieldId == t
                    })
                    if (obj.value != '' && obj.value != '[]') {
                        if (obj.customFieldMess.fieldType == 'selectRadio') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return obj.value == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                        if (obj.customFieldMess.fieldType == 'selectChecked') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return v == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                    }
                }
            },
            // 自定义字段图片列
            customImgSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if (item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            // 自定义图片预览
            costomImgPreview(i, len, list) {
                this.customImgData.visible = true
                this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
                this.customImgData.initial = Number(i) - 1
                this.customImgData.list = list.map(item => {
                    return {
                        name: item.name,
                        url: this.$global.uploadUrl + item.url
                    }
                })
                this.customImgData.num = i - 1
                this.setActiveItem(i - 1)
            },
            setActiveItem(i) {
                if (this.$refs.carousel) {
                    this.$refs.carousel.setActiveItem(i)
                }
            },
            // 图片预览轮播切换
            handleCarousel(v) {
                this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
                this.customImgData.num = v
            },
            // 图片下载
            imgDownLoad() {
                window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
            },
            //pageSize 改变时会触发
            handleSizeChange(val) {
                this.searchForm.limit = val
                this.getWorkOrderList(this.searchForm)
            },
            //currentPage 改变时会触发
            handleCurrentChange(val) {                
                this.searchForm.page = val;
                this.getWorkOrderList(this.searchForm);
            },
            updateTable() {
                this.toUpdateTableKey = !this.toUpdateTableKey
            }
        },
        beforeUpdate() {
            this.$nextTick(() => {
                this.$refs.tabList.doLayout()
            })
        }
    }
</script>

<style lang="less" scoped>
    .tableList {
        padding: 0 20px;

        code {
            font-family: sans-serif;
        }

        .progress {
            display: flex;

            .item_progress {
                display: flex;
                flex-direction: column;

                .progress_circle {
                    display: flex;
                    align-items: center;
                    cursor: pointer;

                    .line {
                        width: 30px;
                        height: 2px;
                        margin: 0px 3px;
                    }

                    .no_c {
                        background-color: rgb(24, 144, 255);
                    }

                    .re_c {
                        background-color: #67C23A;
                    }

                    .no_start {
                        background-color: rgb(230, 230, 230);
                    }
                }

                span {
                    color: #5a5a5a;
                    font-size: 12px;
                    display: inline-block;
                    width: 42px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    text-align: center;
                    white-space: nowrap;
                }

                /deep/ .el-progress-circle {
                    width: 42px !important;
                    height: 42px !important;
                }

                /deep/ .el-progress__text {
                    font-size: 12px !important;
                }
            }
        }

        .circle {
            display: inline-block;
            background: rgb(24, 145, 255);
            margin-right: 10px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }

        .btnCell {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-around;
        }

        .permisColor {
            color: #5a5a5a;
        }

        .workordercode {
            position: relative;

            .urgent {
                position: absolute;
                top: 0;
                left: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;
                width: 12px;
                height: 12px;
                padding: 0 1px 1px 0;
                background-color: #ff3b30;
                color: white;
                border-radius: 0 0 21px 0;
            }
        }

        .status {
            span:nth-of-type(1) {
                display: inline-block;
                vertical-align: middle;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                cursor: pointer;
            }

            span:nth-child(2) {
                display: inline-block;
                width: 28px;
                background-color: rgb(255, 59, 48);
                font-size: 12px;
                text-align: center;
                color: white;
                border-radius: 3px;
            }
        }
    }
</style>